<template>
  <view>
    <el-row :span="24" style="height: 600px">
      <el-col :span="12">
        <terminal v-show="terminalShow" init-log="" context="root" title="执行日志" id="terminal" name="my-terminal" show-log-time @execCmd="onExecCmd" @onClick="tapEvent"></terminal>
        <el-button v-show="!terminalShow" type="primary" @click="showTer">显示日志</el-button>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <el-collapse v-model="activeName" accordion @change="handleChange">
            <el-collapse-item v-for="(item, index) in picList" :title="item.desc" :name="item.desc">
              <div>
                <img :src="picHttp + item.msg" />
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </el-col>
    </el-row>
  </view>
</template>

<script setup>
import { onMounted, defineProps } from "vue";
import Terminal from "vue-web-terminal";
import dayjs from "dayjs";
const emit = defineEmits(["confirm"]);
const picHttp = ref("http://localhost:8000/code/img/");
const picList = ref([]);
const activeName = ref();
const { proxy } = getCurrentInstance();
const props = defineProps({
  taskId: {
    type: String,
  },
});
console.log(props.taskId);
var ws = new WebSocket(`ws://mq.apisev.cn/ws/${props.taskId}`);
const wsStatus = ref(false);
ws.onopen = function (evt) {
  console.log("Connection open ...");
  wsStatus.value = true;
};
const terminalShow = ref(true);
function tapEvent(e){
  console.log(e)
  if(e == 'close'){
    terminalShow.value = false;
  }
}
function showTer(){
  terminalShow.value = true;
}
// 若需要多个回调  实例.addEventListener
// ws.addEventListener('open', function (event) {
//  ws.send('Hello Server!');
// });

ws.onmessage = function (e) {
  console.log("服务器返回的信息: " + e.data);
  let obj = JSON.parse(e.data);
  console.log(obj);
  let name = "my-terminal";
  if (obj.source == "log") {
    let message = {
      type: "normal",
      class: obj.type,
      content: "[" + dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss") + "] | " + obj.msg,
    };
    Terminal.$api.pushMessage(name, message);
  } else if (obj.source == "img") {
    console.log("---------新增图片------------");
    picList.value = picList.value.concat([obj]);
  }
};
//
function handleChange(val) {
  activeName.value = val;
}

// 执行命令执行回调
function onExecCmd(e) {
  let name = "my-terminal"; //  每一个terminal都会定义一个name，详情见前面文档
  let message = {
    type: "normal",
    class: "warning",
    content: "[" + dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss") + "] | " + "日志窗口禁止其余操作",
  };
  Terminal.$api.pushMessage(name, message);
}
</script>
